package com.tarena.lbs.activity.service.impl;

import com.tarena.lbs.activity.dao.repository.ActivityRepository;
import com.tarena.lbs.activity.pojo.param.ActivityAddParam;
import com.tarena.lbs.activity.pojo.po.ActivityPO;
import com.tarena.lbs.activity.pojo.query.ActivityQuery;
import com.tarena.lbs.activity.pojo.vo.ActivityVO;
import com.tarena.lbs.activity.service.ActivityService;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.pojo.dto.AttachDTO;
import com.tarena.lbs.attach.pojo.query.AttachQuery;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import lombok.extern.slf4j.Slf4j;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private ActivityRepository activityRepository;
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private AttachApi attachApi;

    @Override
    public List<ActivityVO> pageList(ActivityQuery query) throws BusinessException {
        log.info("商家活动列表入参{}", query);
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null,new BusinessException("-1","用户未登录"));
        Asserts.isTrue(userPrinciple.getRole() != Roles.SHOP,new BusinessException("-1","用户权限不足"));
        AdminDto adminDto = userApi.getAdminById(userPrinciple.getId());
        if (adminDto == null){
            throw new BusinessException("-1","商家不存在");
        }
        Integer businessId = adminDto.getBusinessId();
        query.setBusinessId(businessId);
        List<ActivityVO> vos = activityRepository.pageList(query);
        return vos;
    }

    @Override
    public ActivityVO activityDetail(Integer id) throws BusinessException {
        log.info("商家活动详情入参{}", id);
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null,new BusinessException("-1","用户未登录"));
        ActivityVO vo = activityRepository.activityDetail(id);
        AttachQuery query = new AttachQuery();
        query.setBusinessId(vo.getBusinessId());
        query.setBusinessType(1);
        List<AttachDTO> imgDtos = attachApi.getAttachInfo(query);
        List<String> imgPics = null;
        for (AttachDTO imgDto : imgDtos){
            // 封装图片地址(存的是uuid 不是具体路径)
            imgPics.add(imgDto.getFileUuid());
        }
        return vo;
    }

    @Override
    public void activityDelete(Integer id) throws BusinessException {
        log.info("商家活动删除入参{}", id);
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null,new BusinessException("-1","用户未登录"));
        Asserts.isTrue(userPrinciple.getRole() != Roles.SHOP,new BusinessException("-1","用户权限不足"));
        activityRepository.activityDelete(id);
    }


    @Override
    public void activitySave(ActivityAddParam param) throws BusinessException, ParseException {
        log.info("商家活动保存入参{}", param);
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null,new BusinessException("-1","用户未登录"));
        Asserts.isTrue(userPrinciple.getRole() != Roles.SHOP,new BusinessException("-1","用户权限不足"));
        AdminDto adminDto = userApi.getAdminById(userPrinciple.getId());
        if (adminDto == null){
            throw new BusinessException("-1","商家不存在");
        }

        // 转换ActivityAddParam为ActivityPO
        ActivityPO activityPO = new ActivityPO();
        // 手动拷贝属性，避免类型不匹配问题
        activityPO.setId(param.getId());
        activityPO.setActivityName(param.getActivityName());
        activityPO.setDescribes(param.getDescribes());
        activityPO.setImgIds(param.getImgIds());
        activityPO.setShopIds(param.getShopIds());
        activityPO.setTargetCustomer(param.getTargetCustomer());
        activityPO.setActivityTarget(param.getActivityTarget());
        activityPO.setDeliveryChannel(param.getDeliveryChannel());
        // 特别注意类型转换：Integer -> String
        activityPO.setRewardCouponId(param.getRewardCouponId());
        activityPO.setShareProfile(param.getShareProfile());
        activityPO.setShareUrl(param.getShareUrl());
        activityPO.setActivityJson(param.getActivityJson());
        activityPO.setMarketingType(param.getMarketingType());
        activityPO.setStatus(1); // 默认启用状态
        activityPO.setRewardType(param.getRewardType());

        // 设置商家ID
        activityPO.setBusinessId(adminDto.getBusinessId());

        // 处理日期转换
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if (param.getStartDate() != null && !param.getStartDate().isEmpty()) {
                Date startDate = sdf.parse(param.getStartDate());
                activityPO.setStartDate(startDate);
            }
            if (param.getEndDate() != null && !param.getEndDate().isEmpty()) {
                Date endDate = sdf.parse(param.getEndDate());
                activityPO.setEndDate(endDate);
            }
        } catch (ParseException e) {
            log.error("日期格式解析错误: ", e);
            throw new BusinessException("-1", "日期格式错误，请使用 yyyy-MM-dd HH:mm:ss 格式");
        }

        // 验证日期逻辑
        if (activityPO.getStartDate() != null && activityPO.getEndDate() != null) {
            if (activityPO.getStartDate().after(activityPO.getEndDate())) {
                throw new BusinessException("-1", "活动开始时间不能晚于结束时间");
            }
        }

        // 设置默认值
        if (param.getId() == null) {
            // 新增活动
            activityPO.setCreateAt(new Date());
        }else {
            activityPO.setUpdateAt(new Date());
        }
        // 保存到数据库
        activityRepository.save(activityPO);
    }
}